#include "sg_label.h"
#include "../lcd_drivers/lcd.h"


static void Refresh(sg_label_t * this);
static size_t Sg_GetTextSize(const char * text);


inline void SgLabel_init(sg_label_t * this)
{
    memset(this, 0, sizeof(sg_label_t));
    this->Color = Lcd_GetColorHex(0XFFFFFF);
    this->FontMode = LCD_FM_OPAQUE;
    this->Font = &SG_DEFAULT_FONT;
}

inline void SgLabel_setColor(sg_label_t * this, lcd_color_t color)
{
    this->Color = color;
}

inline void SgLabel_setFontMode(sg_label_t * this, lcd_font_mode_t fm)
{
    this->FontMode = fm;
}

inline void SgLabel_setFont(sg_label_t * this, const lcd_font_t * font)
{
    this->Font = font;
}

inline void SgLabel_setText(sg_label_t * this, const char * text)
{
    u16 old_height = this->Height;
    u16 old_width = this->Width;
    this->Text = text;
    this->Height = this->Font->AsciiHeight;
    this->Width = (this->Font->AsciiWidth + this->Font->WordSpace) * Sg_GetTextSize(text);
    this->Status = SG_ST_NORMAL;
    if(old_height > 0 && old_width > 0)
    {
        if(this->Height < old_height)
        {
            Lcd_Clear(this->Pos.x, this->Pos.y + this->Height, this->Pos.x + old_width - 1, this->Pos.y + old_height - 1);
        }
        if(this->Width < old_width)
        {
            Lcd_Clear(this->Pos.x + this->Width, this->Pos.y, this->Pos.x + old_width - 1, this->Pos.y + this->Height - 1);
        }
    }
    Refresh(this);
}

static void Refresh(sg_label_t * this)
{
    if(this->Status == SG_ST_NORMAL)
    {
        Lcd_SetPaintColor(this->Color);
        Lcd_SetBgColor(this->BgColor);
        Lcd_SetFontMode(this->FontMode);
        Lcd_SetFont(this->Font);
        Lcd_ShowString(this->Pos.x, this->Pos.y, this->Text);
    }
}


static size_t Sg_GetTextSize(const char * text)
{
    size_t i = 0;
    while(1)
    {
        if(*text == '\0')break;
        i++;
        text++;
    }
    return i;
}


